﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using MyWebPagesStarterKit;
using System.IO;


namespace MyWebPagesStarterKit
{

    /// <summary>
    /// Summary description for CustomHtml
    /// </summary>
    public class CustomHtml : Persistable<CustomHtml.Data>
    {
        public CustomHtml()
        {
            _data.Entries = new DataSet();
            _data.Entries.Tables.Add(new DataTable("Entries"));

            DataColumn primaryKeyColumn = new DataColumn("Guid", typeof(Guid));
            primaryKeyColumn.Unique = true;

            _data.Entries.Tables["Entries"].Columns.Add(primaryKeyColumn);
            _data.Entries.Tables["Entries"].PrimaryKey = new DataColumn[] { primaryKeyColumn };

            _data.Entries.Tables["Entries"].Columns.AddRange(
                new DataColumn[] 
                {
                    new DataColumn("Title", typeof(string)),
                    new DataColumn("Html", typeof(string))
                }
           );
        }

        public DataView GetEntriesFromKey(string key)
        {
            return new DataView(Entries, string.Format("Guid='{0}'", key), "", DataViewRowState.CurrentRows);
        }

        public DataRow GetRowFromKey(string key)
        {
            DataRow row = null;
            DataRow[] foundRows = Entries.Select(string.Format("Guid = '{0}'", key));
            if (foundRows.Length > 0)
                row = foundRows[0];
            return row;
        }

        public DataView GetEntries()
        {
            return new DataView(Entries, null, "Title", DataViewRowState.CurrentRows);
        }

        public DataTable Entries
        {
            get
            {
                return base._data.Entries.Tables["Entries"];
            }
        }

        protected override string GetDataFilename()
        {
            return "~/App_Data/CustomHtml.config";
        }

        private static CustomHtml _instance;

        public static CustomHtml GetInstance()
        {
            if (_instance == null)
            {
                _instance = new CustomHtml();
                if (File.Exists(HttpContext.Current.Server.MapPath(_instance.GetDataFilename())))
                {
                    _instance.LoadData();
                }
            }
            return _instance;
        }


        public struct Data
        {
            public DataSet Entries;
        }
    }
}
